<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>View Activity Records</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link href="./EldercareMasterPage/_finalstyle.css" rel="stylesheet" />
	<link href="./css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link rel="stylesheet" type="text/css" href="./jquery/easyui.css">
	<link rel="stylesheet" type="text/css" href="./jquery/icon.css">    
</head>
<?php
	define('CONFIG_FILE',true);
	include './config.php';
	define('DB_FILE',true);
	
	session_start();
	if (empty($_SESSION["username"])||empty($_SESSION["userType"])) {
		Header("Location: ./Index.php");
		exit();
	}else{
		$userType = $_SESSION["userType"];
	}
	
	// set timeout period in seconds
	$inactive = 7200;
	// check to see if $_SESSION['timeout'] is set
	if (isset($_SESSION["timeout"])) {
		$session_life = time() - $_SESSION["timeout"];
		if ($session_life > $inactive) {
			session_destroy();
			Header("Location: Timeout.php");
		}
	}
	$_SESSION["timeout"] = time();
?>
<body>
	<div class="banner">
	</div>
		<div id="main">
			<div class="left-wrapper">
				<div class="logo">
                <img src="images/eldercare.gif" alt="logo" width="240px" />
				</div>
					<div class="menu-wrapper">
						<div id="cssmenu">
							<?php
								if ($userType == "Therapy Assistant") {
									include_once('./Sidebar/_SidebarTA.php');
								} else if ($userType == "Centre Manager") {
									include_once('./Sidebar/_SidebarCM.php');
								} else {
									include_once('./Sidebar/_SidebarSA.php');
								}
							?>
						</div>
					</div>		
                    <div class="clear"></div>
			</div>
            <div id="content">
				<div class="content2">
					<b style="float:right; margin: 0px 0 0 0">  
						<?php
							if (!empty($_SESSION["centreName"])) {
								$Username = $_SESSION["username"];
								$centreName = $_SESSION["centreName"];
								echo "Welcome, " . $Username . " ! " . $centreName . " Branch";
							} else {
								$Username = $_SESSION["username"];
								echo "Welcome, " . $Username;
							}
						?>
						<input type="submit" class="btn btn-danger" value="Logout" onclick="parent.location = 'logout.php'">
					</b>
					</p>
					<br> 
					<div style="float:center">
					<br>					
					<h3>Activities Records</h3>
					<br>
					<table id="dg" title="Activities Records" class="easyui-datagrid" style="width:auto;height:430px; "
						   url="ViewActRecords/get_ViewActRecords.php"
						   toolbar="#tb" pagination="true" singleSelect ="true"
						   rownumbers="true" fitColumns="true" >
						<thead>
							<tr>
								<th field="NRIC" width="40" sortable="true">NRIC</th>
								<th field="CustomerName" width="80" sortable="true">Name</th>
								<th field="Date" width="40" sortable="true">Date</th>
								<?php
									if ($userType == 'System Admin') {
										echo "<th field='CentreName' width='50' sortable=\"true\">CentreName</th>";
									}
								?>
								<th field="ActivityName" width="50" sortable="true">Activity Name</th>
								<th field="Category" width="50" sortable="true">Category</th>
								<th field="Performance" width="50" sortable="true">Performance</th>
								<th field="Remarks" width="50">Remarks</th>
						<tbody style="display:none">
						<th field ="ActivityRecordID" width="50">ActivityRecordID</th>
						</tbody>
							<?php
								if ($userType != "System Admin") {
									echo "<tbody style='display:none'>
										<th field='CentreName' width='50'>Centre Name</th>
										<th field='ActivityRecordID' width='50' >ActivityRecordID</th>";
								} else {
									echo "<th field='CentreName' width='50'>Centre Name</th>
										<tbody style='display:none'>
										<th field='ActivityRecordID' width='50' >ActivityRecordID</th>";
								}
							?>
						</tr>
						</thead>
					</table>
					<div id="tb" style="padding:3px">
						<?php
							if ($userType != "Therapy Assistant") {
								echo"<a href='#' style='line-height:26px; solid #ccc' class='easyui-linkbutton' iconCls='icon-remove' plain='true' onclick='removeActAtt()'>Remove</a>";
							}
						?>
						<span>NRIC:</span>
						<input id="NRIC" name="NRIC" style="line-height:20px;width:90px;border:1px solid #ccc">
						<span>Name:</span>
						<input id="CustomerName" name="CustomerName" style="line-height:20px;width:125px;border:1px solid #ccc">
						<span>From:</span> 
						<input id="FromDate" name="FromDate" class="easyui-datebox" />
						<span>To:</span> 
						<input id="ToDate" name="ToDate" data-options="formatter:myformatter,parser:myparser" class="easyui-datebox"/>
						<br><span style="padding: 0 36px">&nbsp;</span>
							<?php
								require_once './Tool/DB/SqlDBManager.class.php';
								$sqlDBManager = new SqlDBManager();

								if ($userType == "System Admin") {
									echo"Center: <select name='CentreLocation' id = 'CentreLocation' style=\"width:150px;\"> 
										<option value='0'selected disabled>Select a Centre</option>";
										
										$sql="Select CentreId, CentreName FROM centre";
										$res=$sqlDBManager->queryRows($sql);
										if(!empty($res)){
											for($i=0;$i<count($res);$i++){
												echo "<option value='".$res[$i]['CentreId']."'>".$res[$i]['CentreName']."</option>";
											}
										}									
									echo"</select>";
								}
								//close connection
    							$sqlDBManager->close_connect();
							?>
						<span>Activity:</span>
							<?php
								require_once './Tool/DB/SqlDBManager.class.php';
								$sqlDBManager = new SqlDBManager();
								if ($userType == "System Admin"){
									echo"<select name='ActivityId' id = 'ActivityId' onmouseover=\"showActivity()\" style=\"width:150px;\"> 
										<option value='0'selected disabled >Select an Activity</option>";								
									echo"</select>";
								}else{
									echo"<select name='ActivityId' id = 'ActivityId' style=\"width:150px;\"> 
										<option value='0'selected disabled >Select an Activity</option>";
									$sql="SELECT ActivityId, ActivityName FROM Activity WHERE CentreName=?";
									$parameters=array($centreName);
									$res=$sqlDBManager->queryRows($sql,$parameters);
									if(!empty($res)){
										for($i=0;$i<count($res);$i++){
											echo "<option value='".$res[$i]['ActivityId']."'>".$res[$i]['ActivityName']."</option>";
										}
									}									
									echo"</select>";
									//close connection
    								$sqlDBManager->close_connect();
								}	
							?>
						<a href="#" class="easyui-linkbutton" iconCls="icon-search" onClick="doSearch()">Search</a>
						<a href="#" class="easyui-linkbutton" onClick="findAll()">All</a>
					</div>
					</div>
				</div>
			</div>
			<div class="clear"></div>
		</div>
	<div class="clear"></div>
	<div id="footer">&copy; 2013 MP22 IIT-IT Temasek Polytechnic</div>
</body>
<script type="text/javascript" src="./jquery/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="./jquery/jquery.easyui.min.js"></script>          
<script type="text/javascript">
	$(function(){ 
        $("#FromDate").next().find("input.validatebox-text").attr("readonly","readonly");  
        $("#ToDate").next().find("input.validatebox-text").attr("readonly","readonly");
    });
	$('#FromDate').datebox({
	    formatter : function(date){
	        var y = date.getFullYear();
			var m = date.getMonth()+1;
			var d = date.getDate();
			return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);
	    },
	    parser : function(s){
	        var t = Date.parse(s);
	        if (!isNaN(t)){
	            return new Date(t);
	        } else {
	            return null;
	        }
	    }
	});
	
	function myformatter(date) {
		var y = date.getFullYear();
		var m = date.getMonth() + 1;
		var d = date.getDate();
		return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);
	}
	function myparser(s) {
		if (!s)
			return new Date();
		var ss = (s.split('-'));
		var y = parseInt(ss[0], 10);
		var m = parseInt(ss[1], 10);
		var d = parseInt(ss[2], 10);
		if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
			return new Date(y, m - 1, d);
		} else {
			return new Date();
		}
	}

	function doSearch() {
		//validate search input    
		var flagNRIC=0;	
		var flagCustomerName=0;
		var flagDate=0;
		var flagDateTo=0;
		var flagDateCompare=0;
		var flagCentreLocation=0;
		var flagActivityId=0;
        $.ajax({
            async : false,
            type : "POST",
            url : "./ViewActRecords/validateSearch.php", //the page/method you wanna validate
            data : {
				NRIC: $('#NRIC').val(),
				CustomerName: $('#CustomerName').val(),
				SearchDate: $('[name="FromDate"]').val(),
				SearchDateTo: $('[name="ToDate"]').val(),
				CentreLocation:$('[name="CentreLocation"]').val(),
				ActivityId: $('[name="ActivityId"]').val(),
			},
            success : function(data) {
            	var data = JSON.parse(data);
                flagNRIC=data.flagNRIC;	
				flagCustomerName=data.flagCustomerName;
				flagDate=data.flagDate;
				flagDateTo=data.flagDateTo;
				flagDateCompare=data.flagDateCompare;
				flagCentreLocation=data.flagCentreLocation;
				flagActivityId=data.flagActivityId;
            }
        });
        if(flagNRIC==0){
            $.messager.show({
                title: 'Error',
                msg: 'Invalid Search Input.',
				showType:'fade',
				style:{
					right:'',
					bottom:''
				}
            });
        }else if(flagCustomerName==0){
        	$.messager.show({
                title: 'Error',
                msg: 'Invalid Search Input.',
				showType:'fade',
				style:{
					right:'',
					bottom:''
				}
            });
        }else if(flagDate==0){
        	$.messager.show({
                title: 'Error',
                msg: 'Invalid Search Input.',
				showType:'fade',
				style:{
					right:'',
					bottom:''
				}
            });
        }else if(flagDateCompare==0){
        	$.messager.show({
                title: 'Error',
                msg: 'Please ensure that the End Date is greater than or equal to the Start Date.',
				showType:'fade',
				style:{
					right:'',
					bottom:''
				}
            });
        }else if(flagCentreLocation==0){
        	$.messager.show({
                title: 'Error',
                msg: 'Invalid Search Input.',
				showType:'fade',
				style:{
					right:'',
					bottom:''
				}
            });
        }else if(flagActivityId=0){
        	$.messager.show({
                title: 'Error',
                msg: 'Invalid Search Input.',
				showType:'fade',
				style:{
					right:'',
					bottom:''
				}
            });
        }else{
			$('#dg').datagrid('load', {
				NRIC: $('#NRIC').val(),
				CustomerName: $('#CustomerName').val(),
				SearchDate: $('[name="FromDate"]').val(),
				SearchDateTo: $('[name="ToDate"]').val(),
				CentreLocation:$('[name="CentreLocation"]').val(),
				ActivityId: $('[name="ActivityId"]').val(),
			});
        }
	}

	function findAll() {
		$('#dg').datagrid('load', {
		});
	}
	function removeActAtt() {
		var row = $('#dg').datagrid('getSelected');
		if (row) {
			$.messager.confirm('Confirm Delete Activity Attendance', 'Are you sure you want to remove this activity attendance record?', function(r) {
				if (r) {
					//validate ActivityRecordID Id
					var check = 0;
					$.ajax({
						async : false,
						type : "POST",
						url : "./ViewActRecords/validateRemove.php", //the page/method you wanna validate
						data: {
							ActivityRecordID: row.ActivityRecordID
						},
						success : function(data) {
							check=data;
						}
					});
					if(check==0){
						$.messager.show({
							title: 'Error',
							msg: 'Invalid activity attendance record ID to remove',
							showType:'fade',
							style:{
								right:'',
								bottom:''
							}
						});
					}else{
						$.post('./ViewActRecords/remove_act.php', {ActivityRecordID: row.ActivityRecordID}, function(result) {
							if (result.success) {
								$('#dg').datagrid('reload');	// reload the user data
							} else {
								$.messager.show({// show error message
									title: 'Error',
									msg: result.msg,
									showType:'fade',
									style:{
										right:'',
										bottom:''
									}
								});
							}
						}, 'json');
					}
				}
			});
		}
	}

    function showActivity()
	{
		var xmlhttp;
		if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else
		{// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		if(xmlhttp){
			var centreName = $("#CentreLocation").find("option:selected").text();
			xmlhttp.open("GET","./ViewActRecords/dropdownList.php?q="+centreName,true);
			xmlhttp.onreadystatechange=function(){
				if(this.readyState ==4 && xmlhttp.status==200){
					var data = JSON.parse(xmlhttp.responseText);
					$('#ActivityId')[0].options.length = 1;
					for(var i=0;i<data.length;i++) 
					{	
						var opt = document.createElement('option');				
						opt.value=data[i].activityId;
						opt.innerHTML = data[i].activityName;
						document.getElementById("ActivityId").appendChild(opt);
					}
				}
			}
			xmlhttp.send();
		}	
	}
</script>
</html>